import django
django.setup()

from serverworker import views
import sys
from serverworker.models import testmod, Device_info, Device_attribute,Device_maintenance_log,Alex_day_maintenance
from serverworker.models import organ_index_company,organ_index_scene,organ_index_class,organ_index_project
import os
import random
import uuid
import datetime
import random
import schedule
import time
from django.db.models import Count

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'matrix.settings')  # 添加了环境



def job():
    print("I'm working...")

# 设置任务调度：每10分钟执行一次
#schedule.every(10).minutes.do(job)
schedule.every(3).seconds.do(job)

'''
# 启动调度器
while True:
    schedule.run_pending()
    time.sleep(1)
'''

# https://www.cnblogs.com/zhaoyingjie/p/9234442.html


def test():

    star = datetime.datetime.now().replace(hour=0, minute=0,second=0) +datetime.timedelta(days = -1)
    end = datetime.datetime.now().replace(hour=23, minute=59,second=59) +datetime.timedelta(days = -1)
    yesterday = datetime.datetime.now().date()+datetime.timedelta(days = -1)
    data = Device_maintenance_log.objects.filter(create_time__range=(star,end))
    for i in data.values(): print(i)

    for i in data: print(i.create_time)

    #for i in data: Alex_day_maintenance.objects.create(device_name_id=i['device_name_id'],date=yesterday,times=22)
    res = Device_maintenance_log.objects.values().count()
    print(res)
    #for i in res.values(): print(i)




    # 统计每个device_name_id出现的次数
    res = Device_maintenance_log.objects.filter(create_time__range=(star,end)).values('device_name_id').annotate(count=Count('device_name_id')).order_by('device_name_id')
    print(res)
    # 遍历结果
    for i in res:
        print(f"{i['device_name_id']}: {i['count']}  ")
        Alex_day_maintenance.objects.create(device_name_id=i['device_name_id'], date=yesterday, times=i['count'])

def cron_Alex_day_maintenance():
    #次日统计前一天的数据
    star = datetime.datetime.now().replace(hour=0, minute=0, second=0) + datetime.timedelta(days=-1)
    end = datetime.datetime.now().replace(hour=23, minute=59, second=59) + datetime.timedelta(days=-1)
    yesterday = datetime.datetime.now().date() + datetime.timedelta(days=-1)

    # 统计每个device_name_id出现的次数
    res = Device_maintenance_log.objects.filter(create_time__range=(star, end)).values('device_name_id').annotate(
        count=Count('device_name_id')).order_by('device_name_id')
    print(res)

    # 存入Alex_day_maintenance
    for i in res:
        print(f"{i['device_name_id']}: {i['count']}  ")
        Alex_day_maintenance.objects.create(device_name_id=i['device_name_id'], date=yesterday, times=i['count'])

    ## 联合主键去重，存在则更新，预防多次运行
cron_Alex_day_maintenance()